<?php

namespace App\Models\Api;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class SmsCode extends Model
{
    protected $table = 'sms_code';//表

    public $timestamps = false;

    protected $guarded = [];

    private static $timeout = 600;//验证码过期时间,单位:second

    protected $dates = ['created_at'];

    /** 存入短信验证码
     * @param $mobile
     * @param $code
     */
    public static function put($mobile, $code)
    {
        date_default_timezone_set(config('app.timezone'));
        SmsCode::create([
            'mobile' => $mobile,
            'code' => $code,
            'created_at' => Carbon::now(),
        ]);
    }

    /** 删除验证码
     * @param $mobile
     */
    public static function forget($mobile)
    {
        SmsCode::where('mobile', $mobile)->delete();
    }

    /** 验证手机号与验证码
     * @param $mobile
     * @param $code
     * @return array
     */
    public static function validate($mobile, $code)
    {
        $error = '';//错误提示信息
        $error_code = 0;//0为出错,1为成功

        $sms = SmsCode::where('mobile', $mobile)
            ->orderBy('created_at', 'desc')->first();

        if (is_null($sms)) {
            $error = '请先发送短信';
        } elseif ($sms->created_at->lt(Carbon::now()->subSeconds(SmsCode::$timeout))) {
            $error = '验证码已过期,请重新发送';
        } elseif ($sms->code != $code) {
            $error = '手机号码和验证号码不匹配！';
        } else {
            SmsCode::forget($mobile);//验证通过后,删除记录
            $error_code = 1;
        }

        return ['code' => $error_code, 'error' => $error];
    }

    /** 是否可以发送短信
     * @param $mobile
     * @return bool
     */
    public static function canSend($mobile)
    {
        $sms = SmsCode::where('mobile', $mobile)
            ->orderBy('created_at', 'desc')->first();

        //没有发过短信或者距离上一次发的短信超过了60s,可以发生短信
        if (empty($sms) || $sms->created_at->lt(Carbon::now()->subMinute())) {
            return true;
        }
        return false;
    }
}
